//日志处理
import { Context } from 'vm'
import config from '../config'
import { configure, getLogger } from 'log4js'
import { Next } from 'koa'
import { HttpException } from '../exception/HttpException'

configure(config.log)

class CommonHandle {
  constructor() {}
  // 格式化请求日志
  static formatReqLog(ctx: Context) {
    let text = '------------request start------------ \n'
    let method = ctx.method
    text += `request method: ${method} \n request url: ${ctx.originalUrl} \n`

    if ((method = 'GET')) {
      text += `request data: ${JSON.stringify(ctx.query)} \n`
    } else {
      text += `request data: ${JSON.stringify(ctx.body)} \n`
    }
    text += `ctx all: ${JSON.stringify(ctx)}`
    return text
  }
  // 格式化响应日志
  static formatResLog(ctx: Context, time: any) {
    let text = '------------response start------------ \n'
    text += `response result: ${JSON.stringify(ctx.response.body)} \n`

    text += `response all: ${JSON.stringify(ctx)} \n`

    text += `response time: ${time} \n`
    return text
  }
  // 格式化错误日志
  static formatErrorLog(ctx: Context, error: any, time: any) {
    let text = '------------error start------------ \n'
    text += this.formatResLog(ctx, time)
    text += `error content: ${JSON.stringify(error)}`
    return text
  }
}

class HandleLogger extends CommonHandle {
  constructor() {
    super()
  }

  // 请求日志
  static reqLogger(ctx: Context) {
    getLogger('reqLogger').info(this.formatReqLog(ctx))
  }

  // 相应日志
  static resLogger(ctx: Context, time: any) {
    getLogger('resLogger').info(this.formatResLog(ctx, time))
  }

  // 错误日志
  static errorLogger(ctx: Context, error: any, time: any) {
    getLogger('errLogger').error(this.formatErrorLog(ctx, error, time))
  }
}

export default (options?: any) => {
  return async (ctx: Context, next: Next) => {
    const startTime = new Date()
    let period
    try {
      // 请求日志
      HandleLogger.reqLogger(ctx)
      await next()
      // @ts-ignore
      period = new Date() - startTime
      // 响应日志
      HandleLogger.resLogger(ctx, period)
    } catch (err: any) {
      // @ts-ignore
      period = new Date() - startTime

      HandleLogger.errorLogger(ctx, err, period)
      //抛出异常
      throw new HttpException(
        err.result,
        err.msg,
        err.errorCode,
        err.statusCode,
        err.code
      )
    }
  }
}
